import { useAccess } from '@umijs/max';
import { Button, Popconfirm, PopconfirmProps, Tooltip } from 'antd';
import { ButtonProps } from 'antd/es/button';
import React from 'react';

// 定义 PopconfirmButtonProps 继承自 PopconfirmProps 和 ButtonProps
interface PopconfirmButtonProps extends PopconfirmProps {
  /** 禁用状态提示文本 */
  disabledText?: string;
  /** 按钮的名字 */
  buttonText: string;
  /** 其他按钮属性 */
  buttonProps?: Partial<
    Pick<ButtonProps, Exclude<keyof ButtonProps, 'onClick' | 'title'>>
  >;
  /** 所需权限,eg: ['monitor:online:forceLogout'], 传 [] 的视作不需要权限, 默认不需要权限 */
  permissionsRequired?: string[];
  /** 按钮的操作提示 */
  tooltip?: string;
  /** 点击事件默认不向上传递 */
  stopPropagation?: boolean;
}

const PopconfirmButton: React.FC<PopconfirmButtonProps> = ({
  disabledText,
  buttonText,
  buttonProps,
  permissionsRequired = [],
  tooltip,
  stopPropagation = true,
  ...popconfirmProps
}) => {
  const access = useAccess();

  let dynamicButtonProps: ButtonProps = {};
  if (stopPropagation) {
    dynamicButtonProps = { onClick: (e) => e.stopPropagation() };
  }

  if (!access.hasPermission(permissionsRequired)) {
    // 没有权限的情况下直接不显示
    return <></>;
  }
  const finalButtonProps = {
    ...dynamicButtonProps,
    ...buttonProps,
  };

  if (popconfirmProps?.disabled) {
    return (
      <Tooltip title={disabledText || '当前按钮不可用'}>
        <Button
          icon={buttonProps?.icon}
          {...finalButtonProps}
          disabled={popconfirmProps?.disabled}
        />
      </Tooltip>
    );
  }

  return (
    <Popconfirm {...popconfirmProps}>
      <Tooltip title={tooltip}>
        <Button
          {...finalButtonProps}
          disabled={popconfirmProps?.disabled || buttonProps?.disabled}
        >
          {buttonText}
        </Button>
      </Tooltip>
    </Popconfirm>
  );
};

export default PopconfirmButton;
